package top.yuyufeng.mbuy.service.impl;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.yuyufeng.mbuy.dao.CartDao;
import top.yuyufeng.mbuy.dto.CartDTO;
import top.yuyufeng.mbuy.entity.Cart;
import top.yuyufeng.mbuy.service.ICartService;
import top.yuyufeng.mbuy.utils.PageInfoUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CartServiceImpl implements ICartService {

    @Autowired
    private CartDao cartDao;

    @Override
    public void add(CartDTO cartDTO) {
        CartDTO cartRecord = cartDao.getByUserIdAndProductId(cartDTO.getUserId(), cartDTO.getProductId());
        if (null == cartRecord) {
            Cart cart = new Cart();
            BeanUtils.copyProperties(cartDTO, cart);
            cart.setCreateTime(new Date());
            cart.setUpdateTime(new Date());
            cartDao.insert(cart);
        } else {
            cartRecord.setQuantity(cartRecord.getQuantity() + cartDTO.getQuantity());
            cartRecord.setUpdateTime(new Date());
            cartRecord.setCreateTime(null);
            cartDao.update(cartRecord);
        }

    }

    @Override
    public List<CartDTO> listByUserId(Integer userId) {
        List<CartDTO> result = new ArrayList<>();
        List<Cart> cartList = cartDao.getByUserId(userId);
        for (Cart cart : cartList) {
            CartDTO cartDTO = new CartDTO();
            BeanUtils.copyProperties(cart, cartDTO);
            result.add(cartDTO);
        }

        return result;
    }

    @Override
    public void deleteById(Integer id) {
        cartDao.deleteById(id);
    }

    @Override
    public void deleteByUserId(Integer userId) {
        cartDao.deleteByUserId(userId);
    }

    @Override
    public List<CartDTO> listByUserIdWithDetail(Integer userId) {
        return cartDao.listByUserIdWithDetail(userId);
    }

    @Override
    public void check(Integer userId, Integer id, Integer checked) {
        CartDTO cartRecord = new CartDTO();
        cartRecord.setId(id);
        cartRecord.setChecked(checked);
        cartDao.update(cartRecord);
    }

    @Override
    public List<CartDTO> listByUserIdWithDetailChecked(Integer userId) {
        return cartDao.listByUserIdWithDetailChecked(userId);
    }
}
